package com.ibm.spatiotemp.tools;

import com.fasterxml.jackson.databind.JsonNode;

public class RegionBBox {
	private String[] corners = new String[4];   //bbox=[left, bottom, right, top], such as [0.0, 0.0, 50.0, 100.0]
	private double[] tests;
	
	//[%s,%s,%s,%s]
	public RegionBBox(String bbox) throws STException {
		String temp = null;
		if (bbox.startsWith("[") && bbox.endsWith("]")) {
			temp = bbox.substring(1, bbox.length()-1).trim();
			String[] numbers = temp.split(",");
			if (numbers.length == corners.length) {
				for (int i=0; i<corners.length; i++) {
					corners[i] = numbers[i].trim();
				}
			} else {
				throw new STException(String.format(CoreMessages.STHS0001E, "bbox", bbox));
			}			
			for (int i=0; i<corners.length; i++) {
				try {
					tests[i] = Double.parseDouble(corners[i]);
				} catch (NumberFormatException e) {
					throw new STException(String.format(CoreMessages.STHS0001E, "bbox", bbox));
				}
			}			
		} else {
			throw new STException(String.format(CoreMessages.STHS0001E, "bbox", bbox));
		}
	}
	
	public RegionBBox(double center_x, double center_y, double radis)
	{
		tests = new double[corners.length];
		tests[0] = center_x - radis;
		tests[1] = center_y - radis;
		tests[2] = center_x + radis;
		tests[3] = center_y + radis;
		for (int i = 0; i < tests.length; i++) {
			corners[i] = "" + tests[i];
		}
	}
	
	/*x.min, y.min, x.max, y.max*/
	public double getX_min(){
		return tests[0];
	}
	public double getY_min(){
		return tests[1];
	}
	public double getX_max(){
		return tests[2];
	}
	public double getY_max(){
		return tests[3];
	}
	
	public RegionBBox(JsonNode bboxNode) throws STException {
		if (bboxNode.isArray()) {
			if (bboxNode.size() == corners.length) {
				tests = new double[corners.length];
				for (int i=0; i<corners.length; i++) {
					corners[i] = bboxNode.get(i).asText();					
					try {
						tests[i] = Double.parseDouble(corners[i]);
					} catch (NumberFormatException e) {
						throw new STException(String.format(CoreMessages.STHS0001E, "bbox", bboxNode.toString()));
					}
				}
				if (tests[0] == tests[2] || tests[1] == tests[3]) {
					throw new STException(String.format(CoreMessages.STHS0016E, bboxNode.toString()));
				}
			} else {
				throw new STException(String.format(CoreMessages.STHS0001E, "bbox", bboxNode.toString()));
			}
		} else {
			throw new STException(String.format(CoreMessages.STHS0001E, "bbox", bboxNode.toString()));
		}
	}
	
	
	public String getRegionString() {
		String format = "\'%d polygon ((%s %s, %s %s, %s %s, %s %s, %s %s))\'";
		return String.format(format, Constants.SRID, corners[0], corners[1], 
				corners[0], corners[3], corners[2], corners[3], corners[2], corners[1], corners[0], corners[1]);
	}	

}
